package com.transsion.clouddemo

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.pm.Signature
import android.util.Log
import com.transsion.cloud_client_sdk.CloudSDKManager
import com.transsion.cloud_client_sdk.CloudSdkOptions
import com.transsion.cloud_upload_sdk.utils.Utils
import com.transsion.palmsdk.PalmID
import com.transsion.clouddemo.core.Custom.TransIDManager
import com.transsion.clouddemo.core.Custom.utils.Constants
import com.transsion.clouddemo.core.Custom.utils.GsonUtils
import com.transsion.clouddemo.core.Custom.utils.SPUtils
import com.transsion.clouddemo.core.Custom.utils.ThreadUtils
import com.transsion.clouddemo.core.DataGenerator
import com.transsion.clouddemo.core.config.ConfigFragment.Companion.KEY_ENV
import com.transsion.clouddemo.core.config.LogcatService
import com.transsion.clouddemo.core.network.CloudOkHttpClient.getOkHttpClient
import java.security.MessageDigest

class CloudApplication : Application() {

    companion object {


        @SuppressLint("StaticFieldLeak")
        lateinit var context: Context

        const val PKG_NAME="com.transsion.clouddemo"
        private const val APP_ID = "infinix-cloud"
        private const val VERSION_NAME="1.0.0.1"

        var currentAppId = APP_ID
        var currentScene = "9"
        var currentUseConcurrent = false
        var currentUseThreadPool = false


        fun initCloudSdk(appId: String = APP_ID, scene: String = currentScene, useConcurrent: Boolean = currentUseConcurrent,
                         threadPool: Boolean=currentUseThreadPool) {
            val options1 = CloudSdkOptions.Builder()
                .setPackageName(Constants.getScenePackName(scene))
                .setAppId(appId)
                .setVersionName(VERSION_NAME)
                .setDefaultFileDir(Utils.sdkDirectory())
//                .setSyncDataProcessor(CloudSyncProcessor())
//            .setJsonDataProcessor(CallLogJsonDataProcessor())
                .setSize(1000)
//                .setOkHttpClient(getOkHttpClient())
                .setUseConcurrent(useConcurrent)
                .setIsDebug(true)
                .setScene(scene)
                .build()
            val options2 = CloudSdkOptions.Builder()
                .setPackageName(Constants.getScenePackName(scene))
                .setAppId(appId)
                .setVersionName(VERSION_NAME)
                .setDefaultFileDir(Utils.sdkDirectory())
//                .setSyncDataProcessor(CloudSyncProcessor())
//            .setJsonDataProcessor(CallLogJsonDataProcessor())
                .setExecutor(ThreadUtils.threadPool)
                .setSize(1000)
//                .setOkHttpClient(getOkHttpClient())
                .setUseConcurrent(useConcurrent)
                .setIsDebug(true)
                .setScene(scene)
                .build()
//            UtilsSdkInit.accessToken = SPUtils.getString(TransIDManager.KEY_ACCESS_TOKEN)

            if (threadPool) {
                CloudSDKManager.init(context, options2)
            } else {
                CloudSDKManager.init(context, options1)
            }

            //单独监听TPMS推送回调
//        CloudSDKManager.getInstance().setSyncNewTPMSListener(object : SyncNewTPMSListener {
//            override fun onSyncNewTPMS(scene: String): Boolean {
//                //获取同步的数量
//                CloudSDKManager.getInstance().getNoSyncCount(scene) { ke, info, response ->
//                    if (info.success()) {
//                        Log.e("zhangxin", "数量：${response}")
//                    }
//
//                }
//                //获取同步的数据
//                CloudSDKManager.getInstance().clientSync(scene) { key, info, respose ->
//                    Log.e("zhangxin", "数据： $respose")
//                }
//                return true
//            }
//
//        })
        }

    }

    @SuppressLint("SuspiciousIndentation")
    override fun onCreate() {
        super.onCreate()
        context = this.applicationContext

        //测试使用，正常关闭
//        clearImagesFromExternalStorage()
        //和CloudHomeActivity的onDestroy方法的清理相对应
//        SPUtils.clearAll()
        //初始环境为测试环境
        if (SPUtils.getString(KEY_ENV).isNullOrEmpty()) {
            SPUtils.putString(KEY_ENV, "test")
        }

        //初始化账号SDK
        TransIDManager.init(if (SPUtils.getString(KEY_ENV).equals("test")) PalmID.SERVER_TEST else PalmID.SERVER_ONLINE)

        //初始化云服务SDK
        initCloudSdk()

        //初始化业务场景
        if (SPUtils.getString("appIds").isNullOrEmpty() || SPUtils.getString("scenesName").isNullOrEmpty()
            || SPUtils.getString("scenes").isNullOrEmpty()) {
            SPUtils.putString("appIds",GsonUtils.objectToJson(DataGenerator.appIds))
            SPUtils.putString("scenesName",GsonUtils.objectToJson(DataGenerator.scenesName))
            SPUtils.putString("scenes",GsonUtils.objectToJson(DataGenerator.scenes))
        }

        //初始化上传的数据
//        copyDrawablesToExternalStorage(context)


        //开启日志
        startService(Intent(context, LogcatService::class.java))

        // 使用示例
        val md5Signature = getSignatureMD5(context)
        Log.d("zhangxin", md5Signature ?: "N/A")



    }


    fun getSignatureMD5(context: Context): String? {
        try {
            val packageInfo: PackageInfo = context.packageManager.getPackageInfo(
                context.packageName,
                PackageManager.GET_SIGNATURES
            )
            for (signature: Signature in packageInfo.signatures) {
                val md: MessageDigest = MessageDigest.getInstance("MD5")
                md.update(signature.toByteArray())
                val digest = md.digest()
                val md5 = StringBuilder()
                for (b in digest) {
                    val hex = Integer.toHexString(0xFF and b.toInt())
                    if (hex.length == 1) {
                        md5.append('0')
                    }
                    md5.append(hex)
                }
                return md5.toString()
            }
        } catch (e: Exception) {
            Log.e("SignatureMD5", "Error obtaining MD5", e)
        }
        return null
    }










}

